package servlets;

import entities.ContentEntity;
import entities.ContentFavoritesEntity;
import entities.UserEntity;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 
 * @author andrei costache
 *
 */
public class AddFavoriteContentController extends ContentFavoritesController {

	@Override
	public void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            RequestDispatcher view = null;
            String cid = request.getParameter("cid");
            String redirect = null;
            if (cid != null) {
                ContentEntity content = contentDAO.find(new Long(cid));
                HttpSession session = request.getSession();
                Long l_uid = ((UserEntity)session.getAttribute("user")).getUid();
                Long l_cid = new Long(cid);
                ContentFavoritesEntity favorite = favoritesDAO.findByUidAndCid(l_uid,l_cid);
                String submitted = request.getParameter("submitted");
                if (submitted != null){
                    if (favorite == null) {
                        favorite = new ContentFavoritesEntity();
                        favorite.setCid(l_cid);
                        favorite.setUid(l_uid);
                        favorite.setCreated(System.currentTimeMillis()/1000);
                        favoritesDAO.create(favorite);
                        msg.addStatusMessage("Content has been added to Favorites.");
                    } else {
                        msg.addStatusMessage("Already a favorite content.");
                    }
                }
                request.setAttribute("messages", msg);
                request.setAttribute("favorite", favorite);
                request.setAttribute("content", content);
                view = request.getRequestDispatcher("/jsp/fragments/AddToFavorites.jsp");
            } else {
                view = request.getRequestDispatcher("/jsp/ContentFullView.jsp");
            }
            view.forward(request, response);
    }

}
